package fatesg.soft.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import fatesg.soft.entidade.Pessoa;

@Stateless(name = "dao")
public class Dao<T, PK> implements AbstractDAO<T> {

	@PersistenceContext(unitName = "EJBPU")
	private EntityManager em;

	private Class<?> classe;

	public Dao() {
	}

	public Dao(Class<?> classe) {
		this.classe = classe;
	}

	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

	@SuppressWarnings("hiding")
	public <T> void salvar(T element) {
		try {
			em.merge(element);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("hiding")
	public <T> void editar(T element) {
		try {
			element = em.merge(element);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("hiding")
	public <T> void remover(T element) {
		try {
			element = em.merge(element);
			em.remove(element);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public T obter(Long id, Class clazz) {
		T instance = null;
		try {
			instance = (T) em.find(clazz, id);
			return instance;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	@SuppressWarnings("unchecked")
	public List<T> listar(String nome) {
		try {
			Query sql = em.createQuery("SELECT p FROM " + nome + " p ");
			return sql.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public List<T> listar(String nome, String campoOrder) {
		try {
			Query sql = em.createQuery("SELECT p FROM " + nome
					+ " p order by p." + campoOrder + " desc ");
			return sql.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public List<T> listar(String nome, String campoOrder, String campoBusca,
			String tipo, String where) {
		try {
			Query sql = em.createQuery("SELECT p FROM " + nome + " p WHERE p."
					+ campoBusca + " " + where + " '" + tipo + "' order by p."
					+ campoOrder + " desc ");
			return sql.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Pessoa FindByUser(String login, String senha) {
		Query q = em
				.createQuery("SELECT u FROM Usuario u WHERE u.login = :login AND u.senha = :senha");
		q.setParameter("senha", senha);
		q.setParameter("login", login);
		return (Pessoa) q.getResultList().get(0);
	}
}
